package org.example;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class YootkDemo2 {
    private static final String FILE_PATH = "mutant" + File.separator + "vip" + File.separator + "yootk.txt";

    public static void main(String[] args) {
        File file = new File("F:", FILE_PATH);
        ensureParentDirectoryExists(file);

        try {
            writeToFile(file);
            String result = readFirstContent(file);
            System.out.println(result);
        } catch (IOException e) {
            System.err.println("IO异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void ensureParentDirectoryExists(File file) {
        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }

    private static void writeToFile(File file) throws IOException {
        try (Writer out = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)) {
            out.write("：www.yootk.com\n");
            out.append("：edu.yootk.com");
        }
    }

    /**
     * 读取文件第一行内容并提取有用信息
     *
     * @param file 文件对象
     * @return 提取的第一行内容
     */
    private static String readFirstContent(File file) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
            String firstLine = reader.readLine();
            if (firstLine != null && firstLine.contains("：")) {
                // 提取冒号后的内容
                return firstLine.substring(firstLine.indexOf("：") + 1);
            }
        } catch (IOException e) {
            System.err.println("读取文件失败：" + e.getMessage());
            e.printStackTrace();
        }
        return "";
    }
}
